package com.study.talk.ui.app.change

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import androidx.activity.viewModels
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.lifecycleScope
import com.study.talk.R
import com.study.talk.databinding.ActivityChangePwdBinding
import com.study.talk.ui.app.base.BaseActivity
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.time.delay
import kotlinx.coroutines.withContext
import java.time.Duration

@AndroidEntryPoint
class ChangePwdActivity : BaseActivity() {

    private val binding : ActivityChangePwdBinding by lazy { DataBindingUtil.setContentView(this, R.layout.activity_change_pwd) }

    private val vm by viewModels<ChangePwdViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setSupportActionBar(binding.changePwdToolbar)
        binding.lifecycleOwner = this
        binding.vm = vm
        initView()
    }

    private fun initView() {
        binding.changePwdToolbar.setNavigationOnClickListener { finish() }

        binding.changePwdNewPwd.editText?.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}

            override fun afterTextChanged(s: Editable?) {
                if (binding.changePwdNewPwd.editText?.text.toString().length < 8) {
                    binding.changePwdNewPwd.error = "密码长度必须大于8"
                } else {
                    binding.changePwdNewPwd.error = null
                }
            }
        })
        binding.changePwdOldPwd.editText?.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}

            override fun afterTextChanged(s: Editable?) {
                if (binding.changePwdOldPwd.editText?.text.toString().trim().isEmpty()) {
                    binding.changePwdOldPwd.error = "旧密码不能为空"
                } else {
                    binding.changePwdOldPwd.error = null
                }
            }
        })
        binding.changePwdBt.setOnClickListener {
            vm.submit()
        }
        vm.complete.observe(this) {
            if (it) {
                lifecycleScope.launch(Dispatchers.IO) {
                    delay(Duration.ofSeconds(1))
                    withContext(Dispatchers.Main){
                        finish()
                    }
                }
            }
        }
    }
}